import {
  getSettings,
  setSettings,
  applyTheme,
  populateLanguageSelect,
} from "./settings.js";
import { applyI18n } from "./i18n.js";
import { exportAllData, importAllData } from "./storage.js";

async function init() {
  const settings = await getSettings();
  applyTheme(settings.theme, settings.accentColor);
  await applyI18n(settings.language);

  const themeEl = document.getElementById("optTheme");
  const accentEl = document.getElementById("optAccent");
  const langEl = document.getElementById("optLanguage");
  const encryptEl = document.getElementById("optEncrypt");
  const saveStatus = document.getElementById("saveStatus");

  themeEl.value = settings.theme;
  accentEl.value = settings.accentColor || "#4f46e5";
  encryptEl.checked = !!settings.encryptSensitive;
  await populateLanguageSelect(langEl, settings.language);

  document.getElementById("btnSave").addEventListener("click", async () => {
    await setSettings({
      theme: themeEl.value,
      accentColor: accentEl.value,
      language: langEl.value,
      encryptSensitive: encryptEl.checked,
    });
    applyTheme(themeEl.value, accentEl.value);
    await applyI18n(langEl.value);
    saveStatus.textContent = "Saved";
    setTimeout(() => (saveStatus.textContent = ""), 1500);
  });

  document.getElementById("btnExport").addEventListener("click", async () => {
    const blob = new Blob([JSON.stringify(await exportAllData(), null, 2)], {
      type: "application/json",
    });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = "calculator-data.json";
    a.click();
  });

  const fileInput = document.getElementById("fileImport");
  document
    .getElementById("btnImport")
    .addEventListener("click", () => fileInput.click());
  fileInput.addEventListener("change", async () => {
    const file = fileInput.files?.[0];
    if (!file) return;
    const text = await file.text();
    await importAllData(JSON.parse(text));
    const refreshed = await getSettings();
    applyTheme(refreshed.theme, refreshed.accentColor);
    themeEl.value = refreshed.theme;
    accentEl.value = refreshed.accentColor || "#4f46e5";
    await populateLanguageSelect(langEl, refreshed.language);
  });
}

document.addEventListener("DOMContentLoaded", init);
